<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { request } from '@/api';
// 把 base64 转换成 blob 二进制数据对象
import base64ToBlob from 'b64-to-blob'
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const areaList = ref<AreaColumns>({
  province_list: {
    110000: '北京市',
    120000: '天津市',
  },
  city_list: {
    110100: '北京市',
    120100: '天津市',
  },
  county_list: {
    110101: '东城区',
    110102: '西城区',
    // ....
  },
})
// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
const showBirthdayPopup = ref(false)
const showProfessionPopup = ref(false)
const showAreaPopup = ref(false)
const ProfileInfo = ref<ProfileInfo>({} as ProfileInfo)
const birthday = ref(['','',''])
//修改头像
const onSelectAvatar = async (item: ActionSheetAction, index: number) => {

  if (index == 1) {
    console.log('点击了拍照');
    const dataStr= await mk.pickerCamera()
    onUpdateAvatar(dataStr)
    showToast({ message: '上传成功' })

  } else if (index == 0) {
    console.log('点击了相册');

    const dataStr=await mk.pickerPhoto()
    onUpdateAvatar(dataStr)
    showToast({ message: '上传成功' })
  }
}
//生日触发回调
const onChangeBirthday = (date: { selectedValues: string[] }) => { 
  console.log(birthday.value);
  ProfileInfo.value.birthday = date.selectedValues.join('-')
  showBirthdayPopup.value = false
}
//职业选择触发回调
const onChangeProfession = (date: { selectedValues: string[] }) => {
  ProfileInfo.value.profession = date.selectedValues[0]
  showProfessionPopup.value = false
 }
//地区选择触发回调
const onSelectArea = (data: { 
  selectedValues: string[],
  selectedOptions: { text: string}[] }) => {
  ProfileInfo.value.provinceCode = data.selectedValues[0]
  ProfileInfo.value.cityCode = data.selectedValues[1]
  ProfileInfo.value.countyCode=data.selectedValues[2]
  showAreaPopup.value = false
  ProfileInfo.value.fullLocation=data.selectedOptions.map(item => item.text).join('-')

 }
onMounted(async () => {
  const res = await mk.getAreaColumns()
  areaList.value = res
})
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0 })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  console.log(res);
  ProfileInfo.value = res.data.result
  birthday.value = ProfileInfo.value.birthday.split('-')
  closeToast()
})
// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // 把 base64 字符串转换
    const image = base64ToBlob(data, 'image/jpeg')
    // 后端要求传递 FormData 数据
    const fd = new FormData()
    // 按文档要求准备参数
    fd.append('file', image, Date.now() + '.jpeg')
    // 前端上传文件用 post 请求即可
    const res = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    console.log('上传头像成功', res.data)
    // 更新表单的数据
    ProfileInfo.value.avatar = res.data.result.avatar
    // 查询原生鸿蒙的用户信息
    const user = mk.queryUser()
    // 更新原生鸿蒙的用户信息
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    // 成功弹窗提示
    showToast({ message: '上传成功' })
  } catch {
    // 失败弹窗提示
    showToast({ message: '上传失败' })
  }
}
const onSubmit = async () => {
  showLoadingToast({ message: '正在提交', duration: 0, forbidClick: true })
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile', ProfileInfo.value)
    const userInfo = mk.queryUser()
    userInfo.nickname = ProfileInfo.value.nickname
  userInfo.avatar = ProfileInfo.value.avatar
    mk.updateUser(userInfo)
  closeToast()
  showToast({ message: res.data.msg })
}


</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="ProfileInfo.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 修改头像弹层 -->
    <van-action-sheet v-model:show="showAvatarSheet" :actions="[{ name: '相册' }, { name: '拍照' }]"
      @select="onSelectAvatar" cancel-text="取消" close-on-click-action></van-action-sheet>

    <!-- 生日修改弹窗 -->
    <van-popup v-model:show="showBirthdayPopup" round position="bottom">
      <van-date-picker v-model="birthday" title="选择日期" @cancel="showBirthdayPopup = false" @confirm="onChangeBirthday"
        :min-date="new Date(1980, 1, 1)" :max-date="new Date()"></van-date-picker>
    </van-popup>
    <!-- 地区选择弹窗 -->
    <van-popup v-model:show="showAreaPopup" round position="bottom">
      <van-area title="选择省市区" @cancel="showAreaPopup = false" :area-list="areaList" @confirm="onSelectArea"></van-area>
    </van-popup>

    <!--职业选择弹窗 -->
    <van-popup v-model:show="showProfessionPopup" round position="bottom">
      <van-picker :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false"></van-picker>
    </van-popup>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="ProfileInfo.account" readonly></van-field>
      <van-field label="昵称" v-model="ProfileInfo.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="ProfileInfo.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" v-model="ProfileInfo.birthday" @click="showBirthdayPopup = true" readonly
        placeholder="请选择日期"></van-field>
      <van-field label="所在地" v-model="ProfileInfo.fullLocation" @click="showAreaPopup = true" readonly
        placeholder="请选择所在地"></van-field>
      <van-field label="职业" v-model="ProfileInfo.profession" @click="showProfessionPopup = true" readonly
        placeholder="请选择职业"></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="onSubmit()" block type="primary"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
